
import os

import pandas as pd
import akshare as ak

import stock_display as sd

class CStockTool:
    # 这是一个类变量，属于类本身，而不是类的实例  
    data_dir = "."
    to_csv_encoding = "utf-8-sig"

    # 这是一个初始化方法，当创建类的新实例时自动调用
    def __init__(self) -> None:

        # 设置数据存储目录
        CStockTool.data_dir = os.getcwd() + "/data/"
        if not os.path.isdir(CStockTool.data_dir):
            os.mkdir(CStockTool.data_dir)
            
        pass

    # 类方法，属于类本身
    def print_data_directory(cls):
        print(f'{"data directory: "} {cls.data_dir}')

    def gather_stock_info_from_network(self) -> dict:
        """
        从网络中获取股票信息
        """
        
        zh_a_spot_df = ak.stock_zh_a_spot_em()
        
        # 保存原始数据
        zh_a_spot_df.to_csv(CStockTool.data_dir + "沪深京A股概况.csv", encoding=CStockTool.to_csv_encoding, index=False)
        
        stock_market_value_levels_dict = {
            "1万亿以上": pd.DataFrame(),
            "5千亿-1万亿":pd.DataFrame(),
            "1千亿-5千亿":pd.DataFrame(),
            "5百亿-1千亿":pd.DataFrame(),
            "1百亿-5百亿":pd.DataFrame(),
            "5十亿-1百亿":pd.DataFrame(),
            "5十亿以下":pd.DataFrame()
        }

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] >= 10000e8].sort_values("总市值", ascending=False)
        stock_market_value_levels_dict["1万亿以上"] = temp_df

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 10000e8]
        stock_market_value_levels_dict["5千亿-1万亿"] = temp_df[temp_df["总市值"] >= 5000e8].sort_values("总市值", ascending=False)
        
        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 5000e8]
        stock_market_value_levels_dict["1千亿-5千亿"] = temp_df[temp_df["总市值"] >= 1000e8].sort_values("总市值", ascending=False)

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 1000e8]
        stock_market_value_levels_dict["5百亿-1千亿"] = temp_df[temp_df["总市值"] >= 500e8].sort_values("总市值", ascending=False)

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 500e8]
        stock_market_value_levels_dict["1百亿-5百亿"] = temp_df[temp_df["总市值"] >= 100e8].sort_values("总市值", ascending=False)

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 100e8]
        stock_market_value_levels_dict["5十亿-1百亿"] = temp_df[temp_df["总市值"] >= 50e8].sort_values("总市值", ascending=False)

        temp_df = zh_a_spot_df[zh_a_spot_df["总市值"] < 50e8]
        stock_market_value_levels_dict["5十亿以下"] = temp_df[temp_df["总市值"] > 0].sort_values("总市值", ascending=False)

        for key in stock_market_value_levels_dict:
            stock_market_value_levels_dict[key].to_csv(CStockTool.data_dir + key + ".csv", encoding=CStockTool.to_csv_encoding, index=False)

        return stock_market_value_levels_dict
    
    def gather_stock_index():
        """
        获取股票指数
        """
        index_df = ak.index_stock_info()
        index_df.to_csv(CStockTool.data_dir + "股票指数.csv", encoding=CStockTool.to_csv_encoding, index=False)
        index_df = ak.stock_hk_index_spot_em()
        index_df.to_csv(CStockTool.data_dir + "港股指数行情.csv", encoding=CStockTool.to_csv_encoding, index=False)
    
    def gather_fund_etf()->dict:
        #fund_etf_df = ak.fund_etf_spot_em()
        #fund_etf_df.to_csv(CStockTool.data_dir + "etf.csv", encoding=CStockTool.to_csv_encoding, index=False)
        fund_exchange_df = ak.fund_exchange_rank_em()
        fund_exchange_df.to_csv(CStockTool.data_dir + "场内交易基金排行榜.csv", encoding=CStockTool.to_csv_encoding, index=False)

        qdii_etf_df = fund_exchange_df[fund_exchange_df["基金简称"].str.contains("QDII")]
        qdii_etf_df.to_csv(CStockTool.data_dir + "QDII_ETF.csv", encoding=CStockTool.to_csv_encoding, index=False)
        hk_etf_df = fund_exchange_df[fund_exchange_df["基金简称"].str.contains("港股")]
        hk_etf_df.to_csv(CStockTool.data_dir + "HK_ETF.csv", encoding=CStockTool.to_csv_encoding, index=False)
        other_etf_df = fund_exchange_df[~(fund_exchange_df["基金简称"].str.contains("QDII") | fund_exchange_df["基金简称"].str.contains("港股"))]
        other_etf_df.to_csv(CStockTool.data_dir + "OTHER_ETF.csv", encoding=CStockTool.to_csv_encoding, index=False)

        print(f"{"TOTAL: "} {len(fund_exchange_df)}")
        print(f"{" QDII: "} {len(qdii_etf_df)}")
        print(f"{"   HK: "} {len(hk_etf_df)}")
        print(f"{"OTHER: "} {len(other_etf_df)}")

        return {
            "QDII-ETF": qdii_etf_df,
            "HK-ETF": hk_etf_df,
            "OTHER-ETF": other_etf_df
        }
    
    def gather_fund_etf_quote(hk_etf_df:pd.DataFrame):
        etf_quote_dict = {
            "交易日":[],
            "行情":[]
        }

        for row in hk_etf_df.iterrows:
            ak.fund_etf_hist_em(row["基金代码"], period="daily", start_date="20240101", end_date="20240618")

    def analize_stock_industry_category():
        """
        股票行业分类分析
        """
        file_name = CStockTool.data_dir + "股票行业分类.csv"
        stock_industry_category_df = ak.stock_board_industry_name_em()
        stock_industry_category_df.to_csv(file_name, encoding=CStockTool.to_csv_encoding, index=False)

        category_dict = {"证监会行业分类标准", "巨潮行业分类标准", "申银万国行业分类标准",
                         "新财富行业分类标准", "国资委行业分类标准", "巨潮产业细分标准", "天相行业分类标准", "全球行业分类标准"}
        
        for key in category_dict:
            category_df = ak.stock_industry_category_cninfo(key)
            category_df.to_csv(CStockTool.data_dir + key + ".csv", encoding=CStockTool.to_csv_encoding, index=False)
        
        board_quote_df = ak.stock_board_industry_hist_em(symbol="半导体", start_date="20240101", end_date="20240618")
        board_quote_df.to_csv(CStockTool.data_dir + "半导体行情数据.csv", encoding=CStockTool.to_csv_encoding, index=False)
    
    def gather_board_quote(board_name:str):
        board_quote_df = ak.stock_board_industry_hist_em(symbol=board_name, start_date="20240101", end_date="20240618")
        board_quote_df.to_csv(CStockTool.data_dir + board_name + "行情数据.csv", encoding=CStockTool.to_csv_encoding, index=False)

    def gather_index():
        
        # index_list = {"上证系列指数", "深证系列指数", "指数成份", "中证系列指数"}
        # for index in index_list:
        #     index_spot_df = ak.stock_zh_index_spot_em(index)
        #     index_spot_df.to_csv(CStockTool.data_dir + index + "行情数据.csv", encoding=CStockTool.to_csv_encoding, index=False)

        # index_df = ak.index_stock_info()
        # index_df.to_csv(CStockTool.data_dir + "股票指数列表.csv", encoding=CStockTool.to_csv_encoding, index=False)

        constituent_stock = ak.index_stock_cons("000001")
        constituent_stock.to_csv(CStockTool.data_dir + "上证指数成分股.csv", encoding=CStockTool.to_csv_encoding, index=False)

obj_tool = CStockTool()
obj_tool.print_data_directory()
#dict_df = obj_tool.gather_stock_info_from_network()
#CStockTool.analize_stock_industry_category()
#CStockTool.gather_board_quote("半导体")
#CStockTool.gather_board_quote("消费电子")
CStockTool.gather_index()
